<?php

/**
 * Created by PhpStorm.
 * User: andy
 * Date: 16/3/23
 * Time: 18:38
 */
class Common_Helper {

    /**
     * getTime 获取系统时间
     * @return bool|string [统一系统时间]
     */
    public function getTime() {
        return date("Y-m-d H:i:s");
    }

    /**
     * 姓名中间字符串以*隐藏
     * @param $str
     * @return mixed|string
     */
    public function hideStar($str) { //用户名、邮箱、手机账号中间字符串以*隐藏
        if (!preg_match("[^\x80-\xff]", "$str")) {
            if (mb_strlen($str, 'utf-8') == 2) {
                return mb_substr($str, 0, 1, 'utf-8') . '**';
            } else {
                return mb_substr($str, 0, 1, 'utf-8') . '**' . mb_substr($str, -1, 1, 'utf-8');
            }
        }

        if (mb_strlen($str, 'utf-8') == 2) {
            return mb_substr($str, 0, 1, 'utf-8') . '***';

        } else if(mb_strlen($str, 'utf-8') == 3||mb_strlen($str, 'utf-8') == 4) {
            return mb_substr($str, 0, 1, 'utf-8') . '**' . mb_substr($str, -1, 1, 'utf-8');
        } else {
            return mb_substr($str, 0, 2, 'utf-8') . '**' . mb_substr($str, -1, 2, 'utf-8');
        }

    }

    /**
     * 随机字符串生成
     *
     * @param int $len 需要随机的长度，不要太长
     * @return string
     */
    public function createRandStr($len, $perfix = null) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        return ($perfix ? $perfix : "") . substr(str_shuffle(str_repeat($chars, rand(5, 8))), 0, $len);
    }

    /**
     * 可以统计中文字符串长度的函数
     * @param $str 要计算长度的字符串
     * @return int 字符长度
     */
    function abslength($str) {
        if (empty($str)) {
            return 0;
        }
        if (function_exists('mb_strlen')) {
            return mb_strlen($str, 'utf-8');
        } else {
            preg_match_all("/./u", $str, $ar);
            return count($ar[0]);
        }
    }

    /**
     * 验证邮箱地址
     * @param $email
     * @return bool
     */
    public function validEmail($email = null) {
        $isValid = true;
        if (!is_string($email)) return false;
        $atIndex = strrpos($email, "@");
        if (is_bool($atIndex) && !$atIndex) {
            return false;
        }
        $domain = substr($email, $atIndex + 1);
        $local = substr($email, 0, $atIndex);
        $localLen = strlen($local);
        $domainLen = strlen($domain);
        if ($localLen < 1 || $localLen > 64) {
            // local part length exceeded
            $isValid = false;
        } else if ($domainLen < 1 || $domainLen > 255) {
            // domain part length exceeded
            $isValid = false;
        } else if ($local[0] == '.' || $local[$localLen - 1] == '.') {
            // local part starts or ends with '.'
            $isValid = false;
        } else if (preg_match('/\\.\\./', $local)) {
            // local part has two consecutive dots
            $isValid = false;
        } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
            // character not valid in domain part
            $isValid = false;
        } else if (preg_match('/\\.\\./', $domain)) {
            // domain part has two consecutive dots
            $isValid = false;
        } else if
        (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
            str_replace("\\\\", "", $local))
        ) {
            // character not valid in local part unless
            // local part is quoted
            if (!preg_match('/^"(\\\\"|[^"])+"$/',
                str_replace("\\\\", "", $local))
            ) {
                $isValid = false;
            }
        }
        if ($isValid && !(checkdnsrr($domain, "MX") || checkdnsrr($domain, "A"))) {
            // domain not found in DNS
            $isValid = false;
        }

        return $isValid;
    }

    /**
     * IP地址获取
     *
     * @return string 如：192.168.1.1 失败的情况下，返回空
     */
    public function getClientIp() {
        $unknown = 'unknown';

        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)) {
            $ip = getenv('REMOTE_ADDR');
        } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = '';
        }

        return $ip;
    }

    /**
     * 校验手机号码是否正确
     * @author andy
     * @since 2015-07-21
     * @param string $num
     * @return boolean
     */
    public function validateMobileNo($num) {
        if (!is_numeric($num)) return false;
        if (!preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $num) &&
            !preg_match('/^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$/i', $num)
        ) return false;
        return true;
    }

    /**
     * 校验用户姓名是否正确
     * @author andy
     * @since 2015-07-21
     * @param string $name
     * @return boolean
     */
    public function validateUsername($name) {
        return (preg_match('/^[A-Za-z0-9\x80-\xff]+$/i', $name)) ? true : false;
    }

    /**
     * 校验项目名称是否正确
     * @author andy
     * @since 2015-07-22
     * @param string $name
     * @return boolean
     */
    public function validateProjectname($name) {
        // 暂时限定为中文和英文
        return (preg_match('/^[A-Za-z0-9\x80-\xff\s]+$/i', $name)) ? true : false;
    }

    /**
     * 校验项目pid格式
     * @param $pid
     * @return bool
     */
    public function validatePid($pid) {
        return (preg_match('/^[A-Za-z0-9]{12}$/i', $pid)) ? true : false;
    }


}